Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
Is it okay to declare the db instance as a global variable for accessible at all the time , without need to use "require" statement in node js

I am a beginner in "node js" I am developing an program and I want to use the database model in all For example (something like "wpdb") WordPress Is the best way to create it as a global variable, or to use the require statement as needed?

Please help me get the best answer. Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

No, this is not the best way to handle a db connection. You only want the db open and around for as long as necessary and no longer. Usually this means opening the db connection at the place in your code that can know how long to keep it open and then close the connection after using it.

If you are simply referring to the configuration for opening a DB connection, then you could define that configuration object at application start and then pass it as a parameter to your db instantiation code.

import myUserDbCode from '../myUserDbFile';
import myUserMessagesCode from '../myUserMsgsDbFile';

const dbConfig = {
  dbname: 'myFancyDb',
  serverName: 'myDbServerName',
  connectionTimeout: 60
}

(async () => {

  const userList = await myUserDbCode(dbConfig)
    .then((dbResultSet) => {
      return dbResultSet.data;
    }
  };

  const myUser = userList[42];

  const userMessages = await myUserMessagesCode(dbConfig, myUser)
    .then((dbResultSet) => {
      return dbResultSet.data;
    }
  };

  console.log(userMessages);
})();

I recommend following some DB tutorials that show how to build a complete application to see some patterns about how to handle passing configuration options to code and how to manage DB connections.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda